package com.wanxi.dangdang.filter;


import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Author: 吕永杰
 * @Description:
 * @Date: Created in 2021/8/30
 * @Version: 1.0
 */
@Component
@Order(1)
public class SimpleCORSFilter {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); // 允许任何的head头部
        //springboot 2.4.0以上
//        corsConfiguration.addAllowedOrigin("http://www.hotel.com");//具体服务器
//        corsConfiguration.addAllowedOrigin("http://localhost");

        //或者
         corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedMethod("*"); // 允许任何的请求方法
        corsConfiguration.setAllowCredentials(true);

        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}
